package com.example.ktapplication.model

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.elvishew.xlog.XLog
import com.example.ktapplication.AppGlobals
import com.example.ktapplication.bean.LoginBean
import com.example.ktapplication.bean.LogoutBean
import com.example.ktapplication.state.LoginState
import com.example.ktapplication.state.LogoutState
import com.example.ktapplication.utils.NetworkUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import com.example.ktapplication.net.NetRepository

class LogoutViewModel: ViewModel() {

    private val _state = MutableStateFlow<LogoutState>(LogoutState.OnSuccess(null))
    val state: StateFlow<LogoutState> = _state

   lateinit var mUserName:String
   lateinit var mPwd:String

    fun logout() {
        viewModelScope.launch {
            logout.flowOn(Dispatchers.IO)
                .catch { exception ->
                    _state.value = LogoutState.OnError(exception)
                }
                .collect { data ->
                    _state.value = LogoutState.OnSuccess(data)
                }
        }
    }

    private val logout: Flow<LogoutBean> = flow {
        if (!NetworkUtils.isConnected(AppGlobals.getApplication())){
            throw RuntimeException("网络未连接")
        }
        //网络请求
        val data = NetRepository.instance.service.logout()
        //返回结果
        emit(data)
    }

    override fun onCleared() {
        super.onCleared()
    }
}
